package com.tms.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tms.springboot.result.JsonResult;
import com.tms.springboot.result.ResultCode;
import com.tms.springboot.result.ResultTool;
import com.tms.springboot.service.PdAddressBookService;
import com.tms.springboot.users.pojo.PdAddressBook;
import com.tms.springboot.utils.UUId;
import com.tms.springboot.vo.PdAddressBookCityVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * <p>
 * 地址簿 前端控制器
 * </p>
 *
 * @author author
 * @since 2023-06-29
 */
@RestController
@RequestMapping("/pd-address-book")
public class PdAddressBookController {

    @Autowired
    PdAddressBookService pdAddressBookService;

    //获取用户地址簿
    @GetMapping("/queryaddress")
    public JsonResult login(String id) {

        List<PdAddressBookCityVo> list = pdAddressBookService.listcity(id);
        return ResultTool.success(ResultCode.SUCCESS, list);
    }

    //添加地址簿
    @RequestMapping("/addaddress")
    public JsonResult addaddress(@RequestBody PdAddressBook pdAddressBook) {

        UpdateWrapper updateWrapper = new UpdateWrapper<PdAddressBook>();
        updateWrapper.eq("user_id", pdAddressBook.getUserId());
        //判断是否选择默认,如选择就需要将其他地址改为非默认
        if (pdAddressBook.getIsDefault() == 1) {

            PdAddressBook set = new PdAddressBook();
            set.setIsDefault(0);
            pdAddressBookService.update(set, updateWrapper);
        }
        pdAddressBook.setId(UUId.nextId());
        boolean sum = pdAddressBookService.save(pdAddressBook);
        if (sum) {
            return ResultTool.success(ResultCode.SUCCESS);
        }
        return ResultTool.fail(ResultCode.COMMON_FAIL);
    }

    //修改地址簿
    @RequestMapping("/updateaddress")
    public JsonResult updateaddress(@RequestBody PdAddressBook pdAddressBook) {

        UpdateWrapper updateWrapper = new UpdateWrapper<PdAddressBook>();
        updateWrapper.eq("user_id", pdAddressBook.getUserId());
        //判断是否选择默认,如选择就需要将其他地址改为非默认
        if (pdAddressBook.getIsDefault() == 1) {

            PdAddressBook set = new PdAddressBook();
            set.setIsDefault(0);
            pdAddressBookService.update(set, updateWrapper);
        }
        boolean sum = pdAddressBookService.updateById(pdAddressBook);
        if (sum) {
            return ResultTool.success(ResultCode.SUCCESS);
        }
        return ResultTool.fail(ResultCode.COMMON_FAIL);
    }

    //删除地址
    @GetMapping("/deladdress")
    public JsonResult del(String id) {
        pdAddressBookService.removeById(id);
        return ResultTool.success(ResultCode.SUCCESS);
    }
}
